﻿using AutoMapper;
using Decoration.Api.Comm;
using Decoration.Comm;
using Decoration.IService;
using Decoration.Models;
using Decoration.Models.Dto;
using Decoration.Models.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.IdentityModel.Tokens;

namespace Decoration.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CustomerInfoController : ControllerBase
    {
        private readonly ICustomerInfoService svc;
        private readonly IMapper mapper;

        public CustomerInfoController(ICustomerInfoService svc,IMapper mapper)
        {
            this.svc = svc;
            this.mapper = mapper;
        }

        /// <summary>
        /// 获取全部
        /// </summary>
        /// <returns></returns>
        [HttpGet("getAll")]
        public Result Get()
        {
            var data = svc.Query(o => o.Status == 1);

            return new Result() { code = 1, msg = "成功", data = data };
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("login")]
        public Result CustomerLogin(CustomerLoginDto login)
        {
            CustomerInfo lg = svc.Query(o => o.Tel == login.Tel).FirstOrDefault()!;
            if (lg != null)
            {
                if (lg.Password == login.Password)
                {
                    if (lg.Status == 1)
                    {
                      
                        return new Result() { code = 1, msg = "登录成功", data =lg };
                    }
                    else
                    {
                        return new Result() { code = -1, msg = "账号异常!" };
                    }
                }
                else
                {
                    return new Result() { code = -1, msg = "密码错误!" };
                }
            }
            else
            {
                return new Result() { code = -1, msg = "账号错误!" };
            }
        }
        [HttpPut]
        [Route("updatepwd")]
        public Result updatepwd(CustomerPwdDto pwd)
        {
            if (pwd.YPwd.IsNullOrEmpty() || pwd.XPwd.IsNullOrEmpty())
            {
                return new Result() { code = -1, msg = "参数不完整" };
            }
            CustomerInfo info = svc.Get(o => o.Id == pwd.Id);
            if (info == null)
            {
                return new Result() { code = -1, msg = "客户不存在" };
            }
            //pwd.YPwd = Tools.Md5(pwd.YPwd, "X2");
            if (info.Password != pwd.YPwd)
            {
                return new Result() { code = -1, msg = "原密码错误" };
            }

            //pwd.XPwd = Tools.Md5(pwd.YPwd, "X2");
            info.Password = pwd.XPwd;
            bool shu = svc.Update(info);
            if (shu)
            {
                return new Result() { code = 1, msg = "修改成功" };
            }
            else
            {
                return new Result() { code = -1, msg = "失败" };
            }
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="customerName"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        [HttpGet]
        public PagedResult<CustomerDto> Get(string customerName = "",int? customerType=null, int pageSize = 10, int pageIndex = 1)
        {
            string sql = @"select cus.*
                            ,cusType.DictName as 'CustomerTypeName'
	                        from CustomerInfos cus
	                        inner join vw_dict cusType on cus.CustomerType = cusType.DictValue and cusType.DictTypeName = '客户类型'
	                        where 1=1";

            if (!string.IsNullOrEmpty(customerName)) sql += " and customerName like @customerName";
            if (customerType != null) sql += " and customerType = @customerType";

            
            string countSql = $"select count(*) from ({sql}) ff";

            
            int total = svc.ExecuteScalar<int>(sql, new { customerName = $"%{customerName}%", customerType });

            sql += " order by createTime desc";
            sql += " offset @pageSize*(@pageIndex-1) rows fetch next @pageSize rows only";


            var data = svc.Query<CustomerDto>(sql, new { customerName = $"%{customerName}%", customerType, pageSize, pageIndex });

            return new PagedResult<CustomerDto>() { code = 1, msg = "成功", total = total, data = data };
        }

        /// <summary>
        /// 获取单个
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public Result Get(int id)
        {
            var data = svc.Get(o => o.Id == id);

            if (data == null) return new Result() { code = -1, msg = "数据不存在" };

            return new Result() { code = 1, msg = "成功", data = data };
        }

        [HttpGet("MyId")]
        public PagedResult<CustomerDto> MyGet(int Id)
        {
            string sql = @"select cus.*
                            ,cusType.DictName as 'CustomerTypeName'
	                        from CustomerInfos cus
	                        inner join vw_dict cusType on cus.CustomerType = cusType.DictValue and cusType.DictTypeName = '客户类型'
	                        where cus.Id=@Id";

            var data = svc.Query<CustomerDto>(sql, new {Id=Id});

            return new PagedResult<CustomerDto>() { code = 1, msg = "成功", data = data };
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public Result Post(CustomerPostDto dto)
        {
            var entity = mapper.Map<CustomerInfo>(dto);

            if (svc.Add(entity))
                return new Result() { code = 1, msg = "成功" };
            else
                return new Result() { code = 1, msg = "失败" };
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut]
        public Result Put(int id, CustomerPostDto dto)
        {
            var data = svc.Get(o => o.Id == id);

            if (data == null) return new Result() { code = -1, msg = "数据不存在" };

            var entity = mapper.Map(dto, data);

            if (svc.Update(entity))
                return new Result() { code = 1, msg = "成功"};
            else
                return new Result() { code = -1, msg = "失败" };
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public Result Delete(int id)
        {
            var data = svc.Get(o => o.Id == id);

            if (data == null) return new Result() { code = -1, msg = "数据不存在" };

            data.Status = 0;

            if (svc.Update(data))
                return new Result() { code = 1, msg = "成功" };
            else
                return new Result() { code = -1, msg = "失败" };
        }
    }
}
